package co.com.ejb.security;

/**
* A secure school which may block requests to
* open doors depending upon the EJB Security
* model's configuration
*
* @author <a href="mailto:andrew.rubinger@jboss.org">ALR</a>
* @version $Revision: $
*/
@Singleton
@Local(SecureSchoolLocalBusiness.class)
// Declare the roles in the system
@DeclareRoles({Roles.ADMIN, Roles.STUDENT, Roles.JANITOR})
// By default allow no one access, we'll enable access at a finer-grained level
@RolesAllowed({})
@Startup
public class SecureSchoolBean implements SecureSchoolLocalBusiness {

	private boolean opened = false;
	private boolean frontDoorOpened = false;
	private boolean serviceDoorOpened = false;
	
	/**
	* Hook to the container to get security information
	*/
	@Resource
	private SessionContext context;
	
	
	@Override
	@PostConstruct
	// School is open when created
	@RolesAllowed(Roles.ADMIN)
	public void open() {
		opened = true;
	}

	@Override
	public void close() {
		opened = false;
	}

	@Override
	// Give everyone access to this method, we may restrict them later
	@RolesAllowed({Roles.ADMIN, Roles.STUDENT, Roles.JANITOR})
	public void openFrontDoor() throws SchoolClosedException {

		// If we've reached this point, EJB security has let us through. However,
		// we may want to apply some contextual rules. Because EJB security is
		// declarative at the method level, we use the API to enforce specific logic.
		// Get the caller
		final String callerName = context.getCallerPrincipal().getName();
		// Ensure the school is open
		if (!this.isOpen())
		{
			// School's closed, so only let admins open the door
			if (!context.isCallerInRole(Roles.ADMIN))
			{
				// Kick 'em out
				throw SchoolClosedException.newInstance("Attempt to open the front door after hours " +
						"is prohibited to all but admins, denied to: " + callerName);
			}
		}
		// Log
		System.out.println("Opening front door for: " + callerName);
		frontDoorOpened = true;
	}

	@Override
	@RolesAllowed({Roles.ADMIN, Roles.JANITOR})
	// Students cannot open this door
	public void openServiceDoor() {
		serviceDoorOpened = true;
	}

	@Override
	@PermitAll
	public boolean isOpen() {
		return opened;
	}

}
